package com.aiju.cash.ui.discount;

import android.content.Context;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.InputType;
import android.text.Spanned;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.TextView;

import com.aiju.app.SimpleHttpCallback;
import com.aiju.base.activity.BaseTitleActivity;
import com.aiju.bean.Discount;
import com.aiju.cash.R;
import com.aiju.cash.core.api.DiscountApi;
import com.aiju.cash.util.GsonHelper;
import com.aiju.cash.widgit.DiscountView;
import com.aiju.utils.KeyBoardUtils;
import com.aiju.utils.PriceUtil;
import com.aiju.utils.T;
import com.aiju.widgit.dialog.EditDialog;

import java.util.List;

/**
 * @author: 佐为
 * @date: 2017-05-10 10:38
 * @version: V1.0
 * @Description: 整单减价 整单折扣
 */
public class DiscountWholeActivity extends BaseTitleActivity {

    private DiscountView discountView;
    private GridView discountGridView;

    private String type;  //2 整单减价 1 整单折扣

    private DiscountApi discountApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_discount_whole);
        String title = getIntent().getStringExtra("title");
        setCenterTitle(title);

        discountApi = new DiscountApi(mDialogHelper);
        discountGridView = (GridView) findViewById(R.id.lv_discount_whole);
        discountView = (DiscountView) findViewById(R.id.discount_whole);
        if (title.equals("整单减价")) {
            type = "2";
            discountView.setTitle(title);
            discountView.setContent("开启后，您可以在顾客买单时提供“整单减价”的优惠");
            discountView.setLeftDrawable(R.mipmap.ic_jianjia);
            discountView.getRightImageView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setSelected(!v.isSelected());
                    updateSwitch();
                }
            });
        } else {//整单折扣
            type = "1";
            discountView.setTitle(title);
            discountView.setContent("开启后，您可以在顾客买单时提供“整单折扣”的优惠");
            discountView.setLeftDrawable(R.mipmap.ic_zhekou);
            discountView.getRightImageView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    v.setSelected(!v.isSelected());
                    updateSwitch();
                }
            });
        }
        singleDiscount(type);
    }

    /**
     * 某个优惠折扣列表
     *
     * @param type 类型
     */
    private void singleDiscount(String type) {
        discountApi.setDialogHelper(mDialogHelper);
        discountApi.singleDiscount(type, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                String ext = jsonData.getExt().toString();//开关
                discountView.getRightImageView().setSelected(ext.equals("1") ? true : false);
                List<Discount> discounts = GsonHelper.convertEntities(data, com.aiju.bean.Discount.class);
                DiscountAdapter adapter = new DiscountAdapter(DiscountWholeActivity.this, discounts);
                adapter.setExt(ext);
                discountGridView.setAdapter(adapter);
            }
        });
    }

    /**
     * 创建优惠折扣
     */
    private void creatDiscount(String value) {
        discountApi.setDialogHelper(null);
        discountApi.save(type, "", value, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                T.ToastShort("创建成功");
                singleDiscount(type);
            }
        });
    }

    /**
     * 删除优惠折扣
     *
     * @param id
     */
    private void deleteDiscount(int id) {
        discountApi.setDialogHelper(null);
        discountApi.delete(String.valueOf(id), new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                T.ToastShort("删除成功");
                singleDiscount(type);
            }
        });
    }

    /**
     * 更新某个优惠折扣的开关接口
     */
    private void updateSwitch() {
        discountApi.setDialogHelper(null);
        discountApi.updateSwitch(type, new SimpleHttpCallback() {
            @Override
            protected void onDataSuccess(String data) {
                singleDiscount(type);
            }
        });
    }

    /**
     * 显示创建
     */
    private void showCreatDiscountDalog() {
        String hit;
        final String titile;
        if (type.equals("1")) {
            titile = "新增整单折扣";
            hit = "如九五折输入数字9.5";
        } else {
            titile = "新增整单减价";
            hit = "请输入减价金额";
        }
        final EditDialog editDialog = new EditDialog(this)
                .setLayoutParams()
                .setTitileText(titile)
                .setHit(hit)
                .setInputType(InputType.TYPE_CLASS_NUMBER | InputType.TYPE_NUMBER_FLAG_DECIMAL)
                .setOnEditClick(new EditDialog.OnEditClick() {
                    @Override
                    public void onCancel() {
                    }

                    @Override
                    public void onSubmit(String msg) {
                        KeyBoardUtils.closeKeybord(DiscountWholeActivity.this);
                        if (TextUtils.isEmpty(msg)) {
                            T.ToastShort("请输入折扣/减价规则");
                            return;
                        }
                        creatDiscount(msg);
                    }
                });
        if (type.equals("1")) {
            editDialog.getContentEditText().setFilters(new InputFilter[]{
                    new InputFilter() {
                        @Override
                        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                            String oriValue = dest.toString();
                            StringBuffer sb = new StringBuffer(oriValue);
                            sb.append(source);
                            String newValue = sb.toString();

                            Double aDouble = Double.valueOf(newValue);
                            if (aDouble >= 10 || newValue.length() > 3 || aDouble < 1) {
                                return "";
                            }
                            return source;
                        }
                    }
            });
        } else {
            editDialog.getContentEditText().setFilters(new InputFilter[]{
                    new InputFilter() {
                        @Override
                        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                            String oriValue = dest.toString();
                            StringBuffer sb = new StringBuffer(oriValue);
                            sb.append(source);

                            String newValue = sb.toString();
                            Double aDouble = Double.valueOf(newValue);
                            if (aDouble > 10000) {
                                T.ToastShort("优惠金额不可超过一万元");
                                return "";
                            }
                            if (dest.toString().contains(".")) {
                                int index = dest.toString().indexOf(".");
                                int mlength = dest.toString().substring(index).length();
                                if (mlength == 3) {
                                    return "";
                                }
                            }
                            return source;
                        }
                    }
            });
        }
        editDialog.show();
    }


    private class DiscountAdapter extends BaseAdapter {
        private String ext;
        private Context context;
        private List<Discount> discounts;

        private boolean isEnable() {
            return ext.equals("1");
        }

        public void setExt(String ext) {
            this.ext = ext;
        }

        public DiscountAdapter(Context context, List<Discount> discounts) {
            this.context = context;
            this.discounts = discounts;
        }

        @Override
        public int getCount() {
            return discounts.size() + 1;
        }

        @Override
        public Object getItem(int position) {
            return discounts.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View inflate = LayoutInflater.from(context).inflate(R.layout.item_discount_whole, null);
            TextView textView = (TextView) inflate.findViewById(R.id.tv_discount_name);
            if (!isEnable()) {
                inflate.findViewById(R.id.iv_discount_delete).setVisibility(View.GONE);
            }

            if (position == getCount() - 1) {
                textView.setBackgroundResource(R.mipmap.ic_discount_list_add);
                inflate.findViewById(R.id.iv_discount_delete).setVisibility(View.GONE);
                textView.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (!isEnable()) {
                            return;
                        }
                        if (getCount() == 6) {
                            if (type.equals("1")) {
                                T.ToastShort("最多只能设置五种整单折扣优惠");
                            } else {
                                T.ToastShort("最多只能设置五种整单减价优惠");
                            }
                            return;
                        }
                        showCreatDiscountDalog();
                    }
                });
            } else {
                final Discount discount = discounts.get(position);
                textView.setSelected(ext.equals("1") ? true : false);
                if (discount.getType() == 1) {
                    textView.setText(PriceUtil.formatDiscount(discount.getValue()) + "折");
                    textView.setBackgroundResource(R.drawable.selector_discount_zk);
                } else {
                    textView.setText("减" + PriceUtil.formatDouble(discount.getValue()) + "元");
                    textView.setBackgroundResource(R.drawable.selector_discount_jj);
                }
                inflate.findViewById(R.id.iv_discount_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        deleteDiscount(discount.getId());
                    }
                });
            }
            return inflate;
        }

    }

}
